<template>
    <el-drawer v-model="articleStore.isCollaboratorOpen" title="邀请协作人" direction="rtl" :before-close="handleClose">
        <el-form-item label="协作人">
            <el-select v-model="articleStore.collaboratorId" placeholder="请选择协作人">
                <el-option v-for="user in onlineUsers" :key="user.id" :label="user.name" :value="user.id" />
            </el-select>
            <el-input v-model="sendmeaasge" style="width: 240px;margin-top: 20px;" placeholder="输入想说的话" />
            <el-button style="margin-top: 20px;" @click="send()" type="primary">邀请他</el-button>
        </el-form-item>
    </el-drawer>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useArticleStore } from '../../../stores/article';
import config from '../../../../public/config';
import { getuserMessage } from '../../../api/user';
import { sendArticleCollaborator, addCollaboratorId } from '../../../api/article';



const articleStore = useArticleStore();
const onlineUsers = ref([]); // 存储在线用户信息 { id, name }
const sendmeaasge = ref('')

let socket = null;

// **获取用户名**
const fetchUserNames = async (userIds) => {
    const userList = [];
    const currentUserId = localStorage.getItem("userId"); // 获取当前用户 ID
    for (const id of userIds) {
        if (id.toString() === currentUserId) {
            continue; // 跳过当前用户
        }
        try {
            const params = new URLSearchParams
            params.append("id", id)
            const res = await getuserMessage(params);
            userList.push({ id, name: res.data.username }); // 以 id 作为 key，name 作为 label
        } catch (error) {
            console.error(`获取用户 ${id} 信息失败`, error);
        }
    }
    onlineUsers.value = userList;
};

const initWebSocket = () => {
    socket = new WebSocket(config.WS_ONLineURL);

    socket.onmessage = async (event) => {
        const data = JSON.parse(event.data);
        if (data.type === "onlineUsers") {
            console.log("收到在线用户 ID 列表：", data.users);
            await fetchUserNames(data.users); // 获取用户名
        }
    };

    socket.onclose = () => {
        console.log("WebSocket 连接已关闭，尝试重新连接...");
        setTimeout(initWebSocket, 5000); // 5 秒后重连
    };
};

// **组件挂载时初始化 WebSocket**
onMounted(() => {
    initWebSocket();
});

// **组件卸载时关闭 WebSocket**
onBeforeUnmount(() => {
    if (socket) {
        socket.close();
    }
});

async function send() {
    const params = {
        "articleId": articleStore.articleId,
        "userId": localStorage.getItem("userId"),
        "status": 0,
        "collaboratorId": articleStore.collaboratorId,
        "message": sendmeaasge.value
    }
    await sendArticleCollaborator(params).then(res => {
        if (res.code === 200) {
            const id = new URLSearchParams
            id.append("collaboratorId", articleStore.collaboratorId)
            id.append("id",articleStore.articleId)
            addCollaboratorId(id).then(res => {
                console.log(res.data)
            })
            articleStore.isCollaboratorOpen = false
        }
    })

}

</script>
